package top.kaoshanji.p3ch12a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.*;
import java.util.List;

/**
 * 代码清单-p3ch12a-401页a：使用反射API获取泛型信息的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/6 19:38
 */
public class GenericReflection {

    private static final Logger logger = LogManager.getLogger(GenericReflection.class);

    public static void main(String[] args) throws Exception {
        logger.info("...代码清单-p3ch12a-401页a：使用反射API获取泛型信息的示例...");

        GenericReflection gf = new GenericReflection();
        gf.reflect();

    }

    public void reflect() throws Exception {
        Class<?> clazz = Target.class;

        Method method = clazz.getMethod("create", new Class<?>[]{Object.class});

        // 方法参数信息
        Type paramType = method.getGenericParameterTypes()[0];
        TypeVariable<?> typeVariable = (TypeVariable<?>) paramType;
        String typeVariableName = typeVariable.getName();
        logger.info("...方法参数的名称:{}...", typeVariableName);

        // 方法返回值类型
        Type returnType = method.getGenericReturnType();
        ParameterizedType pType = (ParameterizedType) returnType;
        Type actualType = pType.getActualTypeArguments()[0];
        Type[] bounds = ((WildcardType)actualType).getUpperBounds();
        ParameterizedType boundType = (ParameterizedType) bounds[0];
        Type rawType = boundType.getRawType();
        String rawTypeName = rawType.getTypeName();
        logger.info("...方法返回值类型类型参数的名称:{}...", rawTypeName);

    }

}

class Target<T> {

    public List<? extends Comparable<T>> create(T obj) {
        return null;
    }

}
